﻿using DevExpress.XtraLayout.Utils;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Windows.Forms;
using XuanFe.AppLaunch.Common;
using XuanFe.Database.BLL;
using XuanFe.Database.DAL;
using XuanFe.Database.Model;

namespace XuanFe.AppLaunch
{
    public partial class PreRegisterDetailForm : DevExpress.XtraEditors.XtraForm
    {
        private const string m_ModuleId = "0301";

        private string m_RegisterId;
        private string m_CustomerId;
        private bool m_AllowFollowStaffId;
        private PreRegisterModel preRegister;
        private IRefreshForm m_Form;

        private bool m_IsAdd;
        public PreRegisterDetailForm(string registerId, bool allowFollowStaffId, bool add, IRefreshForm form)
        {
            InitializeComponent();

            this.m_RegisterId = registerId;
            this.m_AllowFollowStaffId = allowFollowStaffId;
            this.m_IsAdd = add;
            this.m_Form = form;
        }

        Nullable<DateTime> NullDateTime = null;
        private DataTable dtAirline = new DataTable();
        private DataTable dtCity = new DataTable();
        private List<PassengerModel> lstPassenger = new List<PassengerModel>();
        private List<IDTypeModel> lstIDType = new List<IDTypeModel>();
        private List<ItemObject> lstVisaType = new List<ItemObject>();
        private List<StaffModel> lstStaffs = new List<StaffModel>();
        private List<ItemObject> lstBookingType = new List<ItemObject>();
        private bool m_Loading = false;
        private ManageState m_ManageState;
        private void BuildAll()
        {
            this.lstBookingType.Clear();
            //this.lstBookingType.AddRange(new ItemObject[] { new ItemObject("现场预订", "LOC") { }, new ItemObject("电话预订", "TEL") { }, new ItemObject("网上预订", "WEB") { } });
            this.lstBookingType.AddRange(new ItemObject[] { new ItemObject("电话预订", "TEL") { }, new ItemObject("网上预订", "WEB") { }, new ItemObject("推广预订", "SEO") { } });

            this.cmbBookingType.Properties.Items.Clear();
            this.cmbBookingType.Properties.Items.AddRange(this.lstBookingType);

            this.cmbBookingType.SelectedIndex = 0;

            this.dtAirline = AirlineDAL.Instance.GetDataSet().Tables[0];
            this.dtCity = CityDAL.Instance.GetDataSet().Tables[0];
            this.lstIDType = IDTypeDAL.Instance.Gets(true);
            this.lstVisaType.Clear();
            this.lstVisaType.AddRange(new ItemObject[] { new ItemObject("旅游签证", "01"), new ItemObject("商务签证", "02"), new ItemObject("探亲签证", "03") });

            this.lstStaffs = StaffDAL.Instance.Gets(true);
            this.cmbFollowStaffId.Properties.Items.Clear();
            this.cmbFollowStaffId.Properties.Items.AddRange(this.lstStaffs);

            int visibleIndex = 0;

            this.sluAirlineId.Properties.View.Columns.Clear();
            this.sluAirlineId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "AIRLINE_ID", Caption = "代码", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluAirlineId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "NATION_NAME", Caption = "国家", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluAirlineId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "AIRLINE_NAME", Caption = "航空公司", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluAirlineId.Properties.DisplayMember = "AIRLINE_NAME";
            this.sluAirlineId.Properties.ValueMember = "AIRLINE_ID";
            this.sluAirlineId.Properties.DataSource = this.dtAirline;

            visibleIndex = 0;
            this.sluDepartureCityId.Properties.View.Columns.Clear();
            this.sluDepartureCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "CITY_ID", Caption = "代码", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluDepartureCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "NATION_NAME", Caption = "国家", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluDepartureCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "CITY_NAME", Caption = "城市", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluDepartureCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "AIRPORT_NAME", Caption = "机场", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluDepartureCityId.Properties.DisplayMember = "CITY_NAME";
            this.sluDepartureCityId.Properties.ValueMember = "CITY_ID";
            this.sluDepartureCityId.Properties.DataSource = this.dtCity;

            visibleIndex = 0;
            this.sluArrivalCityId.Properties.View.Columns.Clear();
            this.sluArrivalCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "CITY_ID", Caption = "代码", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluArrivalCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "NATION_NAME", Caption = "国家", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluArrivalCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "CITY_NAME", Caption = "城市", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluArrivalCityId.Properties.View.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn() { FieldName = "AIRPORT_NAME", Caption = "机场", Visible = true, VisibleIndex = visibleIndex++ });
            this.sluArrivalCityId.Properties.DisplayMember = "CITY_NAME";
            this.sluArrivalCityId.Properties.ValueMember = "CITY_ID";
            this.sluArrivalCityId.Properties.DataSource = this.dtCity;

            this.cmbPassengerIDTypeId.Properties.Items.Clear();
            this.cmbPassengerIDTypeId.Properties.Items.AddRange(this.lstIDType);

            this.cmbVisaType.Properties.Items.Clear();
            this.cmbVisaType.Properties.Items.AddRange(this.lstVisaType);
            if (this.cmbVisaType.Properties.Items.Count != 0)
            {
                this.cmbVisaType.SelectedIndex = 0;
            }
        }
        private void Init()
        {
            this.txtRegisterId.Text = this.m_RegisterId;
            this.txtRegisterTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        private bool LoadPreRegister()
        {
            this.preRegister = PreRegisterDAL.Instance.Get(this.m_RegisterId);
            if (preRegister == null)
            {
                return false;
            }

            this.m_CustomerId = preRegister.CustomerId;

            this.txtRegisterId.Text = preRegister.Id;
            this.txtRegisterTime.Text = preRegister.RegisterTime.ToString("yyyy-MM-dd HH:mm:ss");

            this.cmbBookingType.SelectedItem = this.lstBookingType.Find(delegate (ItemObject item) { return string.Equals(item.Value, preRegister.BookingType); });
            if (this.cmbBookingType.SelectedItem == null)
            {
                this.cmbBookingType.SelectedIndex = 0;
            }

            this.cmbFollowStaffId.SelectedItem = this.lstStaffs.Find(delegate (StaffModel item) { return string.Equals(item.Id, preRegister.FollowStaffId); });
            this.txtCustomerName.Text = preRegister.CustomerName;
            this.txtMobileNumber.Text = preRegister.MobileNumber;
            this.txtTelephone.Text = preRegister.Telephone;
            this.txtEMail.Text = preRegister.EMail;
            this.txtQQ.Text = preRegister.QQ;
            this.txtMSN.Text = preRegister.Msn;
            this.dtBirthday.EditValue = preRegister.Birthday;
            this.txtWeChat.Text = preRegister.WeChat;

            this.sluDepartureCityId.EditValue = preRegister.DepartureCityId;
            this.sluArrivalCityId.EditValue = preRegister.ArrivalCityId;
            this.seTotalPeople.EditValue = preRegister.TotalPeople;
            this.sluAirlineId.EditValue = preRegister.AirlineId;
            this.rdgTravelType.EditValue = preRegister.TravelType;
            this.deDepartureDate.EditValue = preRegister.DepartureDate;
            this.deReturnDate.EditValue = preRegister.ReturnDate;
            this.deReturnDate.Enabled = this.rdgTravelType.SelectedIndex == 1;
            this.dePrintDate.EditValue = preRegister.PrintDate;
            this.cmbVisaType.SelectedItem = this.lstVisaType.Find(delegate (ItemObject item) { return string.Equals(item.Value, preRegister.VisaType); });
            this.cmbPassengerIDTypeId.SelectedItem = this.lstIDType.Find(delegate (IDTypeModel item) { return string.Equals(item.Id, preRegister.IDTypeId); });
            this.txtPassengerIDNumber.Text = preRegister.IDNumber;
            this.dtPassengerExpiryDate.EditValue = preRegister.ExpiryDate;
            this.txtPassengerIDNumber.Enabled = this.dtPassengerExpiryDate.Enabled = this.cmbPassengerIDTypeId.SelectedItem != null;

            this.txtDealDesc.Text = preRegister.DealDesc;
            this.mmRemark.Text = preRegister.Remark;

            if (this.preRegister.Transferred)
            {
                this.lciSave.Visibility = LayoutVisibility.Never;
                if (!this.m_IsAdd)
                {
                    this.lciTransfer.Visibility = LayoutVisibility.Never;
                    this.lciTransferBooking.Visibility = LayoutVisibility.Never;
                }
            }

            return true;
        }
        private bool ValidityCheck()
        {
            this.errorProvider1.ClearErrors();
            string message = string.Empty;
            string v = this.cmbFollowStaffId.EditValue as string;
            if (this.cmbFollowStaffId.SelectedItem != null && !string.IsNullOrEmpty(v) && this.cmbFollowStaffId.SelectedIndex == -1)
            {
                this.errorProvider1.SetError(this.cmbFollowStaffId, "跟进员工不存在");
                this.cmbFollowStaffId.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtCustomerName, false, ref message))
            {
                this.errorProvider1.SetError(this.txtCustomerName, message);
                this.txtCustomerName.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtMobileNumber, true, ref message))
            {
                this.errorProvider1.SetError(this.txtMobileNumber, message);
                this.txtMobileNumber.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtTelephone, true, ref message))
            {
                this.errorProvider1.SetError(this.txtTelephone, message);
                this.txtTelephone.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtEMail, true, ref message))
            {
                this.errorProvider1.SetError(this.txtEMail, message);
                this.txtEMail.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtQQ, true, ref message))
            {
                this.errorProvider1.SetError(this.txtQQ, message);
                this.txtQQ.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtMSN, true, ref message))
            {
                this.errorProvider1.SetError(this.txtMSN, message);
                this.txtMSN.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtWeChat, true, ref message))
            {
                this.errorProvider1.SetError(this.txtWeChat, message);
                this.txtWeChat.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.sluDepartureCityId, true, ref message))
            {
                this.errorProvider1.SetError(this.sluDepartureCityId, message);
                this.sluDepartureCityId.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.sluArrivalCityId, true, ref message))
            {
                this.errorProvider1.SetError(this.sluArrivalCityId, message);
                this.sluArrivalCityId.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.deDepartureDate, true, ref message))
            {
                this.errorProvider1.SetError(this.deDepartureDate, message);
                this.deDepartureDate.Focus();
                return (false);
            }
            if (this.deDepartureDate.EditValue != null && this.deDepartureDate.DateTime.Date < DateTime.Now.Date)
            {
                this.errorProvider1.SetError(this.deDepartureDate, "出发日期不能是过去的日期");
                this.deDepartureDate.Focus();
                return (false);
            }
            if (this.rdgTravelType.SelectedIndex == 1)
            {
                if (Global.Instance.MandatoryFieldEmpty(this.deReturnDate, true, ref message))
                {
                    this.errorProvider1.SetError(this.deReturnDate, message);
                    this.deReturnDate.Focus();
                    return (false);
                }
                if (this.deDepartureDate.EditValue == null && this.deReturnDate.EditValue != null)
                {
                    this.errorProvider1.SetError(this.deDepartureDate, "出发日期不能为空");
                    this.deDepartureDate.Focus();
                    return (false);
                }
                if (this.deDepartureDate.EditValue != null && this.deReturnDate.EditValue == null)
                {
                    this.errorProvider1.SetError(this.deReturnDate, "回程日期不能为空");
                    this.deReturnDate.Focus();
                    return (false);
                }
                if (this.deReturnDate.EditValue != null && this.deReturnDate.DateTime.Date < DateTime.Now.Date)
                {
                    this.errorProvider1.SetError(this.deReturnDate, "回程日期不能是过去的日期");
                    this.deReturnDate.Focus();
                    return (false);
                }
                if (this.deReturnDate.EditValue != null && this.deDepartureDate.DateTime.Date > this.deReturnDate.DateTime.Date)
                {
                    this.errorProvider1.SetError(this.deReturnDate, "回程日期不能早于出发日期");
                    this.deReturnDate.Focus();
                    return (false);
                }
            }
            if (this.cmbPassengerIDTypeId.SelectedIndex != -1)
            {
                if (Global.Instance.MandatoryFieldEmpty(this.txtPassengerIDNumber, true, ref message))
                {
                    this.errorProvider1.SetError(this.txtPassengerIDNumber, message);
                    this.txtPassengerIDNumber.Focus();
                    return (false);
                }
                if (Global.Instance.MandatoryFieldEmpty(this.dtPassengerExpiryDate, true, ref message))
                {
                    this.errorProvider1.SetError(this.dtPassengerExpiryDate, message);
                    this.dtPassengerExpiryDate.Focus();
                    return (false);
                }
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtDealDesc, true, ref message))
            {
                this.errorProvider1.SetError(this.txtDealDesc, message);
                this.txtDealDesc.Focus();
                return (false);
            }

            return (true);
        }
        /// <summary>
        /// 设置界面状态
        /// </summary>
        /// <param name="state"></param>
        private void SetManageState(ManageState state)
        {
            this.m_ManageState = state;

            this.errorProvider1.ClearErrors();

            switch (state)
            {
                case ManageState.Append:
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "关闭(&C)";

                    this.txtRegisterId.Enabled = false;
                    this.txtRegisterTime.Enabled = false;
                    if (this.m_AllowFollowStaffId)
                    {
                        this.cmbFollowStaffId.Enabled = true;
                    }
                    else
                    {
                        this.cmbFollowStaffId.Enabled = false;
                    }
                    this.txtCustomerName.Enabled = true;
                    this.txtMobileNumber.Enabled = true;
                    this.txtTelephone.Enabled = true;
                    this.txtEMail.Enabled = true;
                    this.txtQQ.Enabled = true;
                    this.txtMSN.Enabled = true;
                    this.dtBirthday.Enabled = true;

                    this.sluDepartureCityId.Enabled = true;
                    this.sluArrivalCityId.Enabled = true;
                    this.seTotalPeople.Enabled = true;
                    this.sluAirlineId.Enabled = true;
                    this.rdgTravelType.Enabled = true;
                    this.deDepartureDate.Enabled = true;
                    this.deReturnDate.Enabled = this.rdgTravelType.SelectedIndex == 1;
                    this.dePrintDate.Enabled = true;
                    this.cmbVisaType.Enabled = true;
                    this.cmbPassengerIDTypeId.Enabled = true;
                    this.txtPassengerIDNumber.Enabled = false;
                    this.dtPassengerExpiryDate.Enabled = false;

                    this.txtDealDesc.Enabled = true;
                    this.mmRemark.Enabled = true;

                    this.txtCustomerName.Focus();
                    break;
                case ManageState.Modify:
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "关闭(&C)";

                    this.txtRegisterId.Enabled = false;
                    this.txtRegisterTime.Enabled = false;
                    if (this.m_AllowFollowStaffId)
                    {
                        this.cmbFollowStaffId.Enabled = true;
                    }
                    else
                    {
                        this.cmbFollowStaffId.Enabled = false;
                    }
                    this.txtCustomerName.Enabled = true;
                    this.txtMobileNumber.Enabled = true;
                    this.txtTelephone.Enabled = true;
                    this.txtEMail.Enabled = true;
                    this.txtQQ.Enabled = true;
                    this.txtMSN.Enabled = true;
                    this.dtBirthday.Enabled = true;

                    this.sluDepartureCityId.Enabled = true;
                    this.sluArrivalCityId.Enabled = true;
                    this.seTotalPeople.Enabled = true;
                    this.sluAirlineId.Enabled = true;
                    this.rdgTravelType.Enabled = true;
                    this.deDepartureDate.Enabled = true;
                    this.deReturnDate.Enabled = this.rdgTravelType.SelectedIndex == 1;
                    this.dePrintDate.Enabled = true;
                    this.cmbVisaType.Enabled = true;
                    this.cmbPassengerIDTypeId.Enabled = true;
                    this.txtPassengerIDNumber.Enabled = false;
                    this.dtPassengerExpiryDate.Enabled = false;

                    this.txtDealDesc.Enabled = true;
                    this.mmRemark.Enabled = true;

                    this.txtCustomerName.Focus();
                    break;
                case ManageState.Save:
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;

                    this.txtRegisterId.Enabled = false;
                    this.txtRegisterTime.Enabled = false;
                    this.cmbFollowStaffId.Enabled = false;
                    this.txtCustomerName.Enabled = false;
                    this.txtMobileNumber.Enabled = false;
                    this.txtTelephone.Enabled = false;
                    this.txtEMail.Enabled = false;
                    this.txtQQ.Enabled = false;
                    this.txtMSN.Enabled = false;
                    this.dtBirthday.Enabled = false;

                    this.sluDepartureCityId.Enabled = false;
                    this.sluArrivalCityId.Enabled = false;
                    this.seTotalPeople.Enabled = false;
                    this.sluAirlineId.Enabled = false;
                    this.rdgTravelType.Enabled = false;
                    this.deDepartureDate.Enabled = false;
                    this.deReturnDate.Enabled = false;
                    this.dePrintDate.Enabled = false;
                    this.cmbVisaType.Enabled = false;
                    this.cmbPassengerIDTypeId.Enabled = false;
                    this.txtPassengerIDNumber.Enabled = false;

                    this.dtPassengerExpiryDate.Enabled = false;
                    this.txtDealDesc.Enabled = false;
                    this.mmRemark.Enabled = false;
                    break;
                case ManageState.Browse:
                case ManageState.Cancel:
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "关闭(&C)";

                    this.txtRegisterId.Enabled = false;
                    this.txtRegisterTime.Enabled = false;
                    this.cmbFollowStaffId.Enabled = false;
                    this.txtCustomerName.Enabled = false;
                    this.txtMobileNumber.Enabled = false;
                    this.txtTelephone.Enabled = false;
                    this.txtEMail.Enabled = false;
                    this.txtQQ.Enabled = false;
                    this.txtMSN.Enabled = false;
                    this.dtBirthday.Enabled = false;

                    this.sluDepartureCityId.Enabled = false;
                    this.sluArrivalCityId.Enabled = false;
                    this.seTotalPeople.Enabled = false;
                    this.sluAirlineId.Enabled = false;
                    this.rdgTravelType.Enabled = false;
                    this.deDepartureDate.Enabled = false;
                    this.deReturnDate.Enabled = false;
                    this.dePrintDate.Enabled = false;
                    this.cmbVisaType.Enabled = false;
                    this.cmbPassengerIDTypeId.Enabled = false;
                    this.txtPassengerIDNumber.Enabled = false;
                    this.dtPassengerExpiryDate.Enabled = false;

                    this.txtDealDesc.Enabled = false;
                    this.mmRemark.Enabled = false;
                    break;
            }
        }
        /// <summary>
        /// 添加记录
        /// </summary>
        /// <returns></returns>
        private bool AppendRecord(bool addCustomer, CustomerModel customer)
        {
            try
            {
                this.preRegister = new PreRegisterModel()
                {
                    Id = this.txtRegisterId.Text.Trim(),
                    CustomerId = customer.Id,
                    CustomerName = this.txtCustomerName.Text.Trim(),
                    MobileNumber = this.txtMobileNumber.Text.Trim(),
                    Telephone = this.txtTelephone.Text.Trim(),
                    EMail = this.txtEMail.Text.Trim(),
                    QQ = this.txtQQ.Text.Trim(),
                    Msn = this.txtMSN.Text.Trim(),
                    WeChat = this.txtWeChat.Text.Trim(),
                    TravelType = this.rdgTravelType.SelectedIndex + 1,
                    DepartureCityId = Convert.ToString(this.sluDepartureCityId.EditValue),
                    ArrivalCityId = Convert.ToString(this.sluArrivalCityId.EditValue),
                    AirlineId = Convert.ToString(this.sluAirlineId.EditValue),
                    DepartureDate = this.deDepartureDate.EditValue == null ? NullDateTime : this.deDepartureDate.DateTime,
                    ReturnDate = this.deReturnDate.EditValue == null ? NullDateTime : this.deReturnDate.DateTime,
                    PrintDate = this.dePrintDate.EditValue == null ? NullDateTime : this.dePrintDate.DateTime,
                    IDTypeId = this.cmbPassengerIDTypeId.SelectedItem == null ? string.Empty : ((IDTypeModel)this.cmbPassengerIDTypeId.SelectedItem).Id,
                    IDNumber = this.txtPassengerIDNumber.Text.Trim(),
                    ExpiryDate = this.dtPassengerExpiryDate.EditValue == null ? NullDateTime : this.dtPassengerExpiryDate.DateTime,
                    Birthday = this.dtBirthday.EditValue == null ? NullDateTime : this.dtBirthday.DateTime,
                    VisaType = ((ItemObject)this.cmbVisaType.SelectedItem).Value,
                    TotalPeople = Convert.ToInt32(this.seTotalPeople.Value),
                    DealDesc = this.txtDealDesc.Text,
                    Remark = this.mmRemark.Text,
                    FollowStaffId = this.cmbFollowStaffId.SelectedItem == null ? string.Empty : ((StaffModel)this.cmbFollowStaffId.SelectedItem).Id,
                    RegisterTime = Convert.ToDateTime(this.txtRegisterTime.EditValue),
                    Transferred = false,
                    BookingType = ((ItemObject)this.cmbBookingType.SelectedItem).Value,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                };

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            if (addCustomer)
                            {
                                CustomerDAL.Instance.Insert(tran, customer);
                            }
                            else
                            {
                                CustomerDAL.Instance.UpdateFollowStaff(tran, customer);
                            }
                            PreRegisterDAL.Instance.Insert(tran, this.preRegister);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        /// <summary>
        /// 修改记录
        /// </summary>
        /// <returns></returns>
        private bool ModifyRecord(bool addCustomer, CustomerModel customer)
        {
            try
            {
                this.preRegister = new PreRegisterModel()
                {
                    Id = this.txtRegisterId.Text.Trim(),
                    CustomerId = this.m_CustomerId,
                    CustomerName = this.txtCustomerName.Text.Trim(),
                    MobileNumber = this.txtMobileNumber.Text.Trim(),
                    Telephone = this.txtTelephone.Text.Trim(),
                    EMail = this.txtEMail.Text.Trim(),
                    QQ = this.txtQQ.Text.Trim(),
                    Msn = this.txtMSN.Text.Trim(),
                    WeChat = this.txtWeChat.Text.Trim(),
                    TravelType = this.rdgTravelType.SelectedIndex + 1,
                    DepartureCityId = Convert.ToString(this.sluDepartureCityId.EditValue),
                    ArrivalCityId = Convert.ToString(this.sluArrivalCityId.EditValue),
                    AirlineId = Convert.ToString(this.sluAirlineId.EditValue),
                    DepartureDate = this.deDepartureDate.EditValue == null ? NullDateTime : this.deDepartureDate.DateTime,
                    ReturnDate = this.deReturnDate.EditValue == null ? NullDateTime : this.deReturnDate.DateTime,
                    PrintDate = this.dePrintDate.EditValue == null ? NullDateTime : this.dePrintDate.DateTime,
                    IDTypeId = this.cmbPassengerIDTypeId.SelectedItem == null ? string.Empty : ((IDTypeModel)this.cmbPassengerIDTypeId.SelectedItem).Id,
                    IDNumber = this.txtPassengerIDNumber.Text.Trim(),
                    ExpiryDate = this.dtPassengerExpiryDate.EditValue == null ? NullDateTime : this.dtPassengerExpiryDate.DateTime,
                    Birthday = this.dtBirthday.EditValue == null ? NullDateTime : this.dtBirthday.DateTime,
                    VisaType = ((ItemObject)this.cmbVisaType.SelectedItem).Value,
                    TotalPeople = Convert.ToInt32(this.seTotalPeople.Value),
                    DealDesc = this.txtDealDesc.Text,
                    Remark = this.mmRemark.Text,
                    FollowStaffId = this.cmbFollowStaffId.SelectedIndex == -1 ? string.Empty : ((StaffModel)this.cmbFollowStaffId.SelectedItem).Id,
                    RegisterTime = Convert.ToDateTime(this.txtRegisterTime.EditValue),
                    Transferred = false,
                    BookingType = ((ItemObject)this.cmbBookingType.SelectedItem).Value,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                };

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            if (addCustomer)
                            {
                                CustomerDAL.Instance.Insert(tran, customer);
                            }
                            else
                            {
                                CustomerDAL.Instance.UpdateFollowStaff(tran, customer);
                            }
                            PreRegisterDAL.Instance.Update(tran, this.preRegister);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }
        private bool SaveRecord()
        {
            ManageState state = this.m_ManageState;

            string id = this.txtRegisterId.Text.Trim();
            string customerName = this.txtCustomerName.Text.Trim();
            string mobileNumber = this.txtMobileNumber.Text.Trim();
            bool addCustomer = false;
            CustomerModel customer = null;
            string selectedStaffId = string.Empty;
            string selectedStaffName = string.Empty;
            StaffModel selected = null;
            string customerId = Guid.NewGuid().ToString("N").ToUpper();
            switch (state)
            {
                case ManageState.Append:
                    if (!string.IsNullOrEmpty(mobileNumber) && CustomerDAL.Instance.MobileNumberExist(mobileNumber) && !Global.Instance.QueryDlg(string.Format("电话“{0}”已经存在了，是否登记到该电话的账户上？", mobileNumber)))
                    {
                        this.errorProvider1.SetError(this.txtMobileNumber, "该记录已存在！");
                        this.txtMobileNumber.Focus();
                        return false;
                    }

                    customer = CustomerDAL.Instance.Get(new QueryCustomerModel() { QueryMobileNumber = true, MobileNumber = this.txtMobileNumber.Text.Trim() });
                    if (customer != null)
                    {
                        customerId = customer.Id;
                    }
                    else
                    {
                        addCustomer = true;
                        customer = new CustomerModel()
                        {
                            Id = customerId,
                            Name = this.txtCustomerName.Text.Trim(),
                            Sex = 1,
                            Birthday = DateTime.Now.Date,
                            MobileNumber = this.txtMobileNumber.Text.Trim(),
                            Telephone = this.txtTelephone.Text.Trim(),
                            EMail = this.txtEMail.Text.Trim(),
                            ContactAddress = string.Empty,
                            RegisterTime = DateTime.Now,
                            FollowStaffId = this.cmbFollowStaffId.SelectedItem == null ? string.Empty : ((StaffModel)this.cmbFollowStaffId.SelectedItem).Id,
                            LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                            LastModifiedDate = DateTime.Now,
                        };
                    }

                    selected = this.cmbFollowStaffId.SelectedItem as StaffModel;
                    if (selected != null)
                    {
                        selectedStaffId = selected.Id;
                        selectedStaffName = selected.Name;
                    }
                    if (string.IsNullOrEmpty(customer.FollowStaffId))
                    {
                        customer.FollowStaffId = selectedStaffId;
                    }
                    if (!string.Equals(customer.FollowStaffId, selectedStaffId))
                    {
                        // 最后一次跟进人和所选择的跟进人，不是同一个人
                        //StaffModel staff = StaffDAL.Instance.Get(customer.FollowStaffId);
                        //if (!Global.Instance.QueryDlg(string.Format("该客户的原跟进员工是“{0}({1})”，是否更改为“{2}({3})”？\n【是】表示更新跟进人；【否】表示取消保存，不更新。", staff.Name, staff.Id, selectedStaffName, selectedStaffId)))
                        //{
                        //    return false;
                        //}
                        customer.FollowStaffId = selectedStaffId;
                    }

                    if (!this.AppendRecord(addCustomer, customer))
                    {
                        Global.Instance.ErrorDlg("保存失败！");
                        return false;
                    }
                    this.m_ManageState = ManageState.Modify;
                    StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("新增预登记为“{0} - {1} - {2}”的记录", id, customerName, mobileNumber));
                    break;
                case ManageState.Modify:
                    customer = CustomerDAL.Instance.Get(new QueryCustomerModel() { QueryCustomerId = true, CustomerId = this.preRegister.CustomerId });
                    if (customer != null)
                    {
                        customerId = customer.Id;
                    }
                    else
                    {
                        addCustomer = true;
                        customer = new CustomerModel()
                        {
                            Id = customerId,
                            Name = this.txtCustomerName.Text.Trim(),
                            Sex = 1,
                            Birthday = DateTime.Now.Date,
                            MobileNumber = this.txtMobileNumber.Text.Trim(),
                            Telephone = this.txtTelephone.Text.Trim(),
                            EMail = this.txtEMail.Text.Trim(),
                            ContactAddress = string.Empty,
                            RegisterTime = DateTime.Now,
                            FollowStaffId = this.cmbFollowStaffId.SelectedItem == null ? string.Empty : ((StaffModel)this.cmbFollowStaffId.SelectedItem).Id,
                            LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                            LastModifiedDate = DateTime.Now,
                        };
                    }

                    selected = this.cmbFollowStaffId.SelectedItem as StaffModel;
                    if (selected != null)
                    {
                        selectedStaffId = selected.Id;
                        selectedStaffName = selected.Name;
                    }
                    if (string.IsNullOrEmpty(customer.FollowStaffId))
                    {
                        customer.FollowStaffId = selectedStaffId;
                    }
                    if (!string.Equals(customer.FollowStaffId, selectedStaffId))
                    {
                        // 最后一次跟进人和所选择的跟进人，不是同一个人
                        //StaffModel staff = StaffDAL.Instance.Get(customer.FollowStaffId);
                        //if (!Global.Instance.QueryDlg(string.Format("该客户的原跟进员工是“{0}({1})”，是否更改为“{2}({3})”？\n【是】表示更新跟进人；【否】表示取消保存，不更新。", staff.Name, staff.Id, selectedStaffName, selectedStaffId)))
                        //{
                        //    return false;
                        //}
                        customer.FollowStaffId = selectedStaffId;
                    }

                    if (!this.ModifyRecord(addCustomer, customer))
                    {
                        Global.Instance.ErrorDlg("保存失败！");
                        return false;
                    }
                    StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("修改预登记为“{0} - {1} - {2}”的记录", id, customerName, mobileNumber));
                    break;
            }
            Global.Instance.InfoDlg("保存成功！");
            return true;
        }
        private void TransferBooking(string registerId)
        {
            MainForm main = this.ParentForm as MainForm;
            if (main == null)
            {
                return;
            }

            using (DevExpress.Utils.WaitDialogForm waitdlg = new DevExpress.Utils.WaitDialogForm("正在加载...", "请稍候！"))
            {
                PreRegisterModel preReg = PreRegisterDAL.Instance.Get(this.m_RegisterId);
                if (preReg == null)
                {
                    Global.Instance.ErrorDlg(waitdlg, "找不到预登记的信息");
                    return;
                }
                if (preReg.Transferred)
                {
                    Global.Instance.ErrorDlg(waitdlg, "预登记信息已经转为正式订单");
                    return;
                }
                if (string.IsNullOrEmpty(preReg.FollowStaffId))
                {
                    Global.Instance.ErrorDlg(waitdlg, "尚未分配跟进员工，请保存之后再转正式订单");
                    return;
                }

                CustomerModel customer = CustomerDAL.Instance.Get(new QueryCustomerModel() { QueryCustomerId = true, CustomerId = preReg.CustomerId });
                if (customer == null)
                {
                    Global.Instance.ErrorDlg(waitdlg, string.Format("找不到该客户“{0}”的信息", preReg.CustomerName));
                    return;
                }
                string key = string.Concat("P", registerId);
                EditBookingForm dlg = new EditBookingForm(customer, preReg) { Tag = key };
                Global.Instance.ShowMdiForm<EditBookingForm>(main, dlg, key);
                this.m_Form.RefreshData();
                this.Close();
            }
        }
        private void PreRegisterDetailForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.m_Loading = true;
                if (this.m_IsAdd)
                {
                    this.SetManageState(ManageState.Append);
                }
                else
                {
                    this.SetManageState(ManageState.Modify);
                }

                this.BuildAll();

                if (this.m_IsAdd)
                {
                    this.Init();
                }
                else
                {
                    if (!this.LoadPreRegister())
                    {
                        Global.Instance.ErrorDlg("加载订单信息失败");
                        this.Close();
                        return;
                    }
                }
                this.cmbFollowStaffId_SelectedIndexChanged(null, null);
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
            finally
            {
                this.m_Loading = false;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.ValidityCheck()) return;

                Global.Instance.BeginWait();
                ManageState state = this.m_ManageState;

                this.SaveRecord();
                this.m_Form.RefreshData();
                this.Close();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
            finally
            {
                Global.Instance.EndWait();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void cmbPassengerIDTypeId_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.m_Loading) return;

                IDTypeModel idType = this.cmbPassengerIDTypeId.SelectedItem as IDTypeModel;
                this.txtPassengerIDNumber.Enabled = this.dtPassengerExpiryDate.Enabled = idType != null;
                if (this.txtPassengerIDNumber.Enabled)
                {
                    this.txtPassengerIDNumber.Focus();
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void rdgTravelType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.m_Loading) return;

                this.deReturnDate.Enabled = (this.rdgTravelType.SelectedIndex == 1);
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnTransfer_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.SaveRecord()) return;
                this.TransferBooking(this.m_RegisterId);
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnTransferBooking_Click(object sender, EventArgs e)
        {
            try
            {
                this.TransferBooking(this.m_RegisterId);
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void cmbFollowStaffId_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.btnTransfer.Enabled = this.btnTransferBooking.Enabled = this.cmbFollowStaffId.SelectedIndex != -1;
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void txtMobileNumber_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    CustomerModel customer = CustomerDAL.Instance.Get(new QueryCustomerModel() { QueryMobileNumber = true, MobileNumber = this.txtMobileNumber.Text.Trim() });
                    if (customer == null) return;

                    this.txtCustomerName.Text = customer.Name;
                    this.txtEMail.Text = customer.EMail;
                    this.txtTelephone.Text = customer.Telephone;
                    if (customer.Birthday != null)
                    {
                        this.dtBirthday.DateTime = (DateTime)customer.Birthday;
                    }
                    if (!string.IsNullOrEmpty(customer.FollowStaffId))
                    {
                        // 有跟进人
                        foreach (StaffModel item in this.cmbFollowStaffId.Properties.Items)
                        {
                            if (string.Equals(item.Id, customer.FollowStaffId))
                            {
                                this.cmbFollowStaffId.SelectedItem = item;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }
    }
}
